package org.dylan.bdf.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dylan.bdf.system.entity.Dept;
import org.dylan.bdf.system.entity.User;
import org.dylan.bdf.system.service.SystemService;
import org.dylan.web.model.JsonResult;
import org.dylan.web.plugin.omui.model.SimpleTreeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/system/menu")
public class MenuController {

	@Autowired
	private SystemService systemService;

	@RequestMapping({"","index"})
	public String index(){
		return "system/menu";
	}
	
	@RequestMapping("userMenu")
	@ResponseBody
	public List<SimpleTreeModel<Dept>> treeData(HttpServletRequest request,
			@RequestParam(required = false) Map<String, Object> params) {
		List<SimpleTreeModel<Dept>> result = new ArrayList<SimpleTreeModel<Dept>>();
		for (Dept dept : systemService.getAllDepts()) {
			result.add(convertTreeModel(dept));
		}
		return result;
	}

	private SimpleTreeModel<Dept> convertTreeModel(Dept dept) {
		SimpleTreeModel<Dept> treeModel = new SimpleTreeModel<Dept>(
				dept.getId(), dept.getName(), dept);
		if (dept.getParent() != null) {
			treeModel.setPid(dept.getParent().getId());
		}
		return treeModel;
	}

	@RequestMapping("edit")
	public String edit(HttpServletRequest request,
			@RequestParam(required = false) String id, ModelMap model) {
		User user = null;
		if (StringUtils.isNotBlank(id)) {
			user = systemService.findUser(id);
		}
		model.addAttribute("user", user);
		return "system/user-form";
	}

	@RequestMapping("save")
	public String save(User user) {
		// 给予初始的密码
		systemService.saveUser(user);
		return "system/user-form";
	}

	@RequestMapping("ajaxSave")
	@ResponseBody
	public JsonResult<SimpleTreeModel<Dept>> ajaxSave(Dept dept) {
		if (dept.getParent() != null
				&& StringUtils.isBlank(dept.getParent().getId())) {
			dept.setParent(null);
		}
		systemService.saveDept(dept);
		JsonResult<SimpleTreeModel<Dept>> result = new JsonResult<SimpleTreeModel<Dept>>();
		result.setData(convertTreeModel(dept));
		return result;
	}
}
